/*
 * @Author: your name
 * @Date: 2021-08-08 14:09:54
 * @LastEditTime: 2021-11-20 11:01:04
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /blogServe/src/middleware/auth.middleware.js
 */
const jwt = require('jsonwebtoken');

const errorTypes = require('../constants/error-types');
const userService = require('../service/user.service');
const authService = require('../service/auth.service');
const md5password = require('../utils/password-handle');
const { PUBLIC_KEY } = require('../app/config');

const verifyLogin = async (ctx, next) => {
  // 获取用户名和密码
  const { name, password } = ctx.request.body;

  // 判断用户名和密码是否为空
  if(!name || !password) {
    const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED);
    return ctx.app.emit('error', error, ctx);
  }

  // 判断用户是否存在
  const result = await userService.getUserNames(name);
  const user = result[0];
  if(!user) {
    const error = new Error(errorTypes.USER_DOES_NOT_EXISTS);
    return ctx.app.emit('error', error, ctx);
  }
  // 判断密码是否和数据库中一致
  if(md5password(password) !== user.password) {
    const error = new Error(errorTypes.PASSWORD_IS_INCORRENT);
    return ctx.app.emit('error', error, ctx);
  }
  ctx.user = user;
  await next();
}

/**
 * 授权认证
 * @param {*} ctx 
 * @param {*} next 
 */
const verifyAuth = async (ctx, next) => {
  console.log("验证token");
  // 获取token
  const authorization = ctx.headers.authorization;
  if(!authorization) {
    const error = new Error(errorTypes.UNAUTHORIZATION);
    return ctx.app.emit('error', error, ctx);
  }
  const token = authorization.replace('Bearer ', '');

  // 验证token
  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"]
    });

    ctx.user = result;
    await next();
    console.log(66);
  } catch(err) {
    const error = new Error(errorTypes.UNAUTHORIZATION);
    return ctx.app.emit('error', error, ctx);
  }

}

// 判断是否有权限修改动态
const verifyPermission = async (ctx, next) => {
  console.log('验证修改权限');
  // 获取参数
  const { momentId } = ctx.params;
  const { id } = ctx.user;
  // 查询是否具备修改权限
  try {
    const isPermission = await authService.checkMoment(momentId, id);
    if(!isPermission) throw new Error();
    await next();
  } catch(err) {
    const error = new Error(errorTypes.UNPERMISSION);
    return ctx.app.emit('error', error, ctx);
  }
}

module.exports = {
  verifyLogin,
  verifyAuth,
  verifyPermission
}